package com.example.exam.shiro;

import com.example.exam.user.model.UserBean;
import com.example.exam.user.service.UserService;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;

public class ShiroCredentialsMatcher extends SimpleCredentialsMatcher {
	@Autowired
	private UserService sysUserService;
	@Override
	public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
		UsernamePasswordToken utoken = (UsernamePasswordToken) token;
		// 所需加密的参数 即 用户输入的密码
		String inputPwd = String.valueOf(utoken.getPassword());
		// [盐] 一般为用户名 或 随机数
		String account = utoken.getUsername();
		UserBean user = sysUserService.selectId(account);
		String salt = user.getSalt();
		// 加密次数
		int hashIterations = 2;
		SimpleHash sh = new SimpleHash("md5", inputPwd, salt, hashIterations);
		String strsh = sh.toHex();
		// 打印最终结果 //获得数据库中的密码
		String dbPassword = (String) getCredentials(info);
		// 进行密码的比对
		return this.equals(strsh, dbPassword);
		// return this.equals(source, dbPassword);
	}
}
